<template>
  <div class="consensus bg-gray">
    <h3 class="title">
      {{addressInfo.address}}
      <span v-show="addressInfo.alias"> | {{addressInfo.alias}}</span>
      <i class="iconfont icon-fuzhi clicks" @click="copy(addressInfo.address)"></i>
    </h3>
    <div class="cb"></div>
    <el-tabs v-model="consensusActive" @tab-click="handleClick" class="w1200">
      <el-tab-pane :label="$t('consensus.consensus9')" name="consensusFirst">
        <div class="node" v-loading="allNodeLoading">
          <!-- <div class="node_info" v-for="item in searchData" :key="item.agentId">
            <h4 class="bg-gray">
              <i class="iconfont iconwo" v-show="item.isNew"></i>&nbsp;
              <span class="uppercase">{{item.agentId}}</span>&nbsp;
              <i class="iconfont"
                 :class="item.status ===0 ? 'icondaigongshi fred' : 'icongongshizhong fCN'"></i>
              <i class="follow clicks" :class="item.isCollect ? 'el-icon-star-on fCN':'el-icon-star-off'"
                 @click="collect(item)"></i>
            </h4>
            <ul class="bg-white click" @click="toUrl('consensusInfo',item.txHash)">
              <li>{{$t('public.alias')}}<span>{{item.agentAlias}}</span></li>
              <li>{{$t('public.commission')}} <span>{{item.commissionRate}}%</span></li>
              <li>{{$t('public.totalStake')}}<span>{{item.totalDeposit}}</span></li>
              <li>{{$t('public.participants')}}<span>{{item.depositCount}}</span></li>
              <li>{{$t('public.deposit')}}<span>{{item.deposit}}</span></li>
              <li>{{$t('public.credit')}}<span>{{item.creditValue}}</span></li>
            </ul>
          </div> -->
          <div class="node_info" v-for="(item, index) in allNodeData" :key="index">
            <h4 class="bg-gray">
              <span class="uppercase">Node{{(index+1)}}</span>&nbsp;
              <router-link :to="'/consensus/newConsensus?addressp='+item.address" class="adddeleg">加入节点</router-link>
            </h4>
            <ul class="bg-white click">
              <li>{{item.address}}</li>
              <li>{{$t('public.totalStake')}}<span v-if="item.delegate_count">{{item.delegate_count / 1000000}}</span><span v-else>0</span></li>
              <li>{{$t('public.participants')}}<span v-if="item.delegateAccount">{{item.delegateAccount.length}}</span><span v-else>0</span></li>
              <li>{{$t('public.commission')}}<span v-if="item.delegateAccount">{{item.delegateAccount[0].delegate_count / 1000000}}</span><span v-else>0</span></li>
              <li>{{$t('public.deposit')}}<span v-if="item.delegateAccount">{{item.delegateAccount[item.delegateAccount.length-1].delegate_count / 1000000}}</span><span v-else>0</span></li>
            </ul>
          </div>
          <div class="cb"></div>
        </div>
      </el-tab-pane>
      <el-tab-pane :label="$t('consensus.consensus11')" name="consensusSecond">
        <div class="node">
          <div class="node_info" v-for="(item, index) in myNodeData" :key="index">
            <h4 class="bg-gray">
              <span class="uppercase">Node{{(index+1)}}</span>&nbsp;
              <span class="adddeleg">退出节点</span>
            </h4>
            <ul class="bg-white click">
              <li>{{item.delegate_address}}</li>
              <li>{{$t('public.totalStake')}}<span v-if="item.delegate_count">{{item.delegate_count / 1000000}}</span><span v-else>0</span></li>
              <li>{{$t('tab.tab1')}}<span>{{item.rank}}</span></li>
              <li>{{$t('public.time')}}<span>{{item.newtime}}</span></li>
            </ul>
          </div>
          <div class="cb"></div>
        </div>
      </el-tab-pane>
    </el-tabs>    
    <Password ref="password" @passwordSubmit="ExitDelegation"></Password>
  </div>
</template>

<script>
  import {copys, addressInfo, formatDate, passwordVerification} from '@/api/util'
  import Password from '@/components/PasswordBar'

  export default {
    name: 'consensus',
    data() {
      return {
        consensusActive: 'consensusFirst',
        //节点信息
        nodeCount: {agentCount: 0, totalCount: 0},
        //Altoro 信息
        nulsCount: {consensusTotal: 0},

        allNodeData: [],//所有节点信息
        allNodeLoading: false,//所有节点信息加载动画
        addressInfo: [], //账户信息
        agentAsset: JSON.parse(sessionStorage.getItem('info')),//pocm合约单位等信息
        isNew: true,//账户是否已经创建了节点
        pageIndex: 1, //页码
        pageSize: 500, //每页条数
        pageTotal: 0,//总页数
        myNodeData: [],//我的节点信息
        setInterval: null,//定时器变量
      };
    },
    created() {
      this.addressInfo = addressInfo(1);
      setInterval(() => {
        this.addressInfo = addressInfo(1);
      }, 500);
    },
    mounted() {
      setTimeout(() => {
        this.getConsensusNodes(this.pageIndex, this.pageSize, this.nodeTypeRegion);
        //this.getConsensusInfoByAddress(this.pageIndex, this.pageSize, this.addressInfo.address);
      }, 600);
    },
    destroyed() {
      clearInterval(this.setInterval);
    },
    computed: {

    },
    watch: {
      addressInfo(val, old) {
        if (val.address !== old.address && old.address) {
          this.isNew = false;
          this.getConsensusNodes(this.pageIndex, this.pageSize, this.nodeTypeRegion);
          this.getConsensusInfoByAddress(this.pageIndex, this.pageSize, this.addressInfo.address);
        }
      }
    },
    components: {
      Password,
    },
    methods: {

      /**
       * 所有共识列表信息
       * @param pageIndex
       * @param pageSize,
       * @param type
       **/
      getConsensusNodes(pageIndex, pageSize, type) {
        this.allNodeLoading = true;
        this.$post('/wallet/delegateList?visible=true', 'getConsensusNodes', [pageIndex, pageSize, type])
          .then((response) => {
            console.log('共识列表',response);
            if (response.delegates.length > 0) {
              // itme.totalDeposit = Number(timesDecimals(itme.totalDeposit)).toFixed(3);
              this.allNodeData = response.delegates;
              this.allNodeLoading = false;
            }
          })
          .catch((error) => {
            console.log("getConsensusNodes:" + error);
            this.allNodeLoading = true;
          });

      },

      /**
       * 我的节点（根据地址获取共识信息）
       * @param pageIndex
       * @param pageSize
       * @param address
       **/
      getConsensusInfoByAddress(pageIndex, pageSize, address) {
        const params = {
              address: address,
              visible: "true"
          }
        this.$post('/wallet/getaccount', 'getAccountConsensus', params)
          .then((response) => {
            console.log('我的委托',response);
            if (response.delegate) {
                const v = response.delegate;
                for(const i in response.delegate) {
                  const element = formatDate(v[i].timestamp);
                  v[i]['newtime'] = element;
                }
                this.myNodeData = v;
            }
          })
          .catch((error) => {
            console.log("getAccountConsensus:" + error);
          });
      },

      /**
       * 退出委托
       * @param delegate_address
       * @param owner_address
       * @param password
       */
      async ExitDelegation(delegate_address, owner_address, password){
        let passwordInfo = await passwordVerification(this.addressInfo, this.$md5(password));
        if (passwordInfo.success) {
          console.log('密码正确')
          const params = {
              delegate_address: delegate_address,
              owner_address: this.addressInfo.address,
              password: this.$md5(password),
              visible: "true"
          }
          await this.$post('/wallet/undelegateaccount', 'getAccountConsensus', params)
            .then((response) => {
              console.log('退出委托',response);
              if (response.delegate) {
                  const v = response.delegate;
                  for(const i in response.delegate) {
                    const element = formatDate(v[i].timestamp);
                    v[i]['newtime'] = element;
                  }
                  this.myNodeData = v;
              }
            })
            .catch((error) => {
              console.log("getAccountConsensus:" + error);
            });
        } else {
          this.$message({message: this.$t('address.address13'), type: 'error', duration: 1000});
        }
      },

      /**
       * 连接跳转
       * @param name
       * @param params
       */
      toUrl(name, params) {
        console.log(name,params);
        let newQuery = {};
        if (name === 'consensusInfo') {
          newQuery = {hash: params}
        } else {
          newQuery = {consensusLock: params}
        }
        this.$router.push({
          name: name,
          query: newQuery
        })
      },

      /**
       * 复制方法
       * @param sting
       **/
      copy(sting) {
        copys(sting);
        this.$message({message: this.$t('public.copySuccess'), type: 'success', duration: 1000});
      },

      /**
       * tab 切换
       * @param tab
       */
      handleClick(tab) {
        this.consensusActive = tab.name;
        if (tab.name === 'consensusFirst') {
          this.getConsensusNodes(this.pageIndex, this.pageSize, this.nodeTypeRegion);
        } else {
          this.getConsensusInfoByAddress(this.pageIndex, this.pageSize, this.addressInfo.address);
        }
      }
    }
  }
</script>

<style lang="less">
  @import "./../../assets/css/style";

  .consensus {
    .adddeleg{
      float: right;
      cursor: pointer;
    }
    .card {
      margin: -20px auto 0;
      height: 200px;
      .left, .right {
        width: 590px;
      }
    }
    .node {
      margin: 0 0 100px 0;
      .node_info {
        border: @BD1;
        width: 370px;
        height: 175px;
        margin: 20px 20px 0 0;
        float: left;
        &:nth-child(4n) {
          margin: 20px 0 0 0;
        }
        h4 {
          height: 32px;
          line-height: 32px;
          padding: 0 20px;
          .follow {
            float: right;
            padding-top: 5px;
          }
        }
        ul {
          padding: 0 0 2px 0;
          li:first-child{
            text-align: center;
            padding: 0;
            font-size: 14px;
          }          
          li {
            height: 23px;
            line-height: 23px;
            padding: 0 0 0 50px;
            font-size: 12px;
            span {
              display: block;
              float: right;
              text-align: left;
              width: 140px;
            }
          }

        }
      }
    }
  }
</style>
